#include "vchar.h"
#include "utils.h"
#include "string.h"
void vchar_init(vchar *str)
{
    str->len = 0;
    str->__alloced_len = 0;
    str->str = NULL;
}

void vchar_append(vchar *str, const char ch)
{
    str->len++;
    if ((str->len + 1) > str->__alloced_len)
    {
        str->__alloced_len = (str->__alloced_len > 0) ? str->__alloced_len * 2: 2;
        str->str = (char *)xrealloc(str->str, sizeof(char) * str->__alloced_len);
    }
    str->str[str->len - 1] = ch;
    str->str[str->len] = 0;
}



void vchar_append_str(vchar *dest, const char *str)
{
    if (dest->len == 0)
        vchar_append(dest, 0);
    int s_len = strlen(str);
    dest->len += s_len + 2;
    if (dest->len > dest->__alloced_len)
    {
        while (dest->len > dest->__alloced_len)
            dest->__alloced_len = (dest->__alloced_len > 0) ? dest->__alloced_len * 2: 1;
        dest->str = (char *)xrealloc(dest->str, sizeof(char) * dest->__alloced_len);
    }
    dest->str = strncat(dest->str, str, (s_len) * sizeof(char));
}

vchar vchar_itoa(int n)
{
    vchar res;
    vchar_init(&res);
    int sign = -n;
    if (sign < 0)
        n = -n;
    while (n > 0)
    {
        vchar_append(&res, n % 10 + '0');
        n /= 10;
    }
    if (sign < 0)
        vchar_append(&res, '-');

    for (int i = 0, j = res.len - 1; i < j; i++, j--)
    {
        char c = res.str[i];
        res.str[i] = res.str[j];
        res.str[j] = c;
    }
    return res;
}

void vchar_clear(vchar *str)
{
    //if (str->str != NULL && str->__alloced_len > 0)
      //  free(str->str);
    str->len = 0;
}

void vchar_free(vchar *str)
{
    if (str->str != NULL && str->__alloced_len > 0)
       free(str->str);
}
